import { Input, Checkbox, Button, Form } from "antd";
import SvgIcon from "@/components/SvgIcon";
import { Link, useNavigate } from "react-router-dom";
import type { FormProps } from "antd";
import { useEffect, useState } from "react";
import { getStoreItem, setStoreItem } from "@/util/storage";
import { login, getUserInfo } from "@/api/xhr/user/index";
import { queryPublicKey } from "@/api/xhr/common/index";
import { useDispatch } from "react-redux";
import mysocket from "@/api/socket/initSocket";
import ForgotPasswordModal from "@/components/ForgotPasswordModal";
import { message } from "antd";

type FieldType = {
  userAccount?: string;
  password?: string;
  remember?: string;
};

const Login = function () {
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  const navgator = useNavigate();
  const [buttonLoading, setButtonLoading] = useState<boolean>(false);
  const [forgotPasswordVisible, setForgotPasswordVisible] = useState(false);

  const onFinish: FormProps<FieldType>["onFinish"] = values => {
    setButtonLoading(true);
    if (values.remember) {
      setStoreItem(
        "userPassword",
        {
          userAccount: values.userAccount,
          password: values.password
        },
        true
      );
    }
    if (values.userAccount && values.password) {
      // const encrypt = new JSEncrypt();
      // encrypt.setPublicKey(getStoreItem("publicKey").publicKey || "");
      login({
        userAccount: values.userAccount,
        password: values.password
      })
        .then(async () => {
          const res =
            (values.userAccount &&
              (await getUserInfo({ userAccount: values.userAccount }))) ||
            null;
          if (res) {
            dispatch({ type: "user/setUser", payload: res.data });
            setStoreItem("userinfo", JSON.stringify(res.data));
            mysocket.socketConnect();
            navgator("/home");
          }
        })
        .finally(() => {
          setButtonLoading(false);
        });
    }
  };

  useEffect(() => {
    const userPassword: { userAccount: string; password: string } =
      getStoreItem("userPassword");
    if (userPassword) {
      form.setFieldsValue({
        userAccount: userPassword.userAccount,
        password: userPassword.password
      });
    }
    queryPublicKey(null).then(res => {
      setStoreItem("publicKey", {
        publicKey: res.data.publicKey
      });
    });
  }, []);

  // 处理忘记密码
  const handleForgotPassword = () => {
    setForgotPasswordVisible(true);
  };
  
  // 密码重置成功
  const handleResetSuccess = (userAccount: string, password: string) => {
    setForgotPasswordVisible(false);
    message.success("密码已重置，已自动填充账号和密码，请点击登录");
    
    // 自动填充表单
    form.setFieldsValue({
      userAccount,
      password,
      remember: true
    });
  };

  return (
    <>
      <div className="h-full flex flex-col justify-center box-border p-[20px]">
        <div className="text-left">
          <span className="text-4xl text-cyan-400">X</span>
          聊天室
        </div>
        <div className="flex items-center justify-around">
          <SvgIcon name="login" className="h-96 w-96"></SvgIcon>
          <div className="p-5 text-left box-border">
            <h1 className="mb-2 text-[30px] font-medium text-zinc-900">
              欢迎回来~~~
            </h1>
            <p className="mb-7 text-neutral-700 text-xs">
              请先登录后开启和大家的畅聊之旅途
            </p>
            <Form form={form} onFinish={onFinish} autoComplete="off">
              <div className="login-input">
                <div className="px-3 py-2 flex items-center hover:bg-[#7575750d]">
                  <SvgIcon
                    name="username"
                    className="h-[24px] w-[24px]"
                  ></SvgIcon>
                  <div className="ml-2 text-xs">
                    <div className="text-xs text-left text-[#666]">账号:</div>
                    <Form.Item<FieldType>
                      className="mb-0"
                      name="userAccount"
                      rules={[
                        {
                          required: true,
                          message: "请输入你的账号!"
                        }
                      ]}
                    >
                      <Input
                        allowClear
                        size="small"
                        variant="borderless"
                        className="border-0 p-0"
                      />
                    </Form.Item>
                  </div>
                </div>
                <div className="px-3 py-2 flex items-center hover:bg-[#7575750d]">
                  <SvgIcon
                    name="password"
                    className="h-[24px] w-[24px]"
                  ></SvgIcon>
                  <div className="ml-2 text-xs">
                    <div className="text-xs text-left text-[#666]">密码:</div>
                    <Form.Item<FieldType>
                      className="mb-0"
                      name="password"
                      rules={[
                        { required: true, message: "请输入你的密码!" },
                        { min: 6, message: "密码至少6位!" },
                        { max: 10, message: "密码最长10位!" }
                      ]}
                    >
                      <Input.Password
                        allowClear
                        size="small"
                        variant="borderless"
                        className="border-0 p-0"
                      />
                    </Form.Item>
                  </div>
                </div>
              </div>
              <div className="px-3 text-xs flex justify-between items-center my-1 text-[#666]">
                <Form.Item<FieldType>
                  name="remember"
                  valuePropName="checked"
                  className="mb-0"
                >
                  <Checkbox className="text-xs text-[#666]">记住我</Checkbox>
                </Form.Item>
                <span className="cursor-pointer" onClick={handleForgotPassword}>忘记密码？</span>
              </div>
              <div className="my-7 text-xs flex items-center text-[#666]">
                <Form.Item className="mb-0">
                  <Button
                    type="primary"
                    shape="round"
                    className="mr-5"
                    htmlType="submit"
                    loading={buttonLoading}
                  >
                    登录
                  </Button>
                </Form.Item>

                <Link to={"/register"}>
                  <Button shape="round">注册</Button>
                </Link>
              </div>
            </Form>
            <div className="my-7 text-xs flex items-center text-[#666]">
              <span>更多登录方式</span>
            </div>
          </div>
        </div>
      </div>
      
      {/* 忘记密码模态框 */}
      <ForgotPasswordModal
        open={forgotPasswordVisible}
        onCancel={() => setForgotPasswordVisible(false)}
        onSuccess={handleResetSuccess}
      />
    </>
  );
};

export default Login;
